package com.lxw.report.meta.excel.handler;

import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import com.lxw.report.meta.excel.annotation.RemarkData;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

import java.lang.reflect.Field;

/**
 * @author lxw
 * @time 2022/3/30 15:37
 */
public class LocalRowWriteHandler implements RowWriteHandler {

    private Class classZ;

    public LocalRowWriteHandler(Class classZ){
        this.classZ = classZ;
    }

    @Override
    public void afterRowDispose(RowWriteHandlerContext context) {
        if (BooleanUtils.isTrue(context.getHead())) {
            Sheet sheet = context.getWriteSheetHolder().getSheet();
            Drawing<?> drawingPatriarch = sheet.createDrawingPatriarch();
            //读取注解信息
            Field[] fields = this.classZ.getDeclaredFields();
            // 循环判断哪些字段有下拉数据集，并获取
            for(int i =0;i<fields.length;i++){
                Field field = fields[i];
                // 解析注解信息
                RemarkData remarkData = field.getAnnotation(RemarkData.class);
                if(null != remarkData){
                    // 获取固定下拉信息
                    String value = remarkData.value();
                    if(StringUtils.isNotBlank(value)){
                        Comment comment =
                                drawingPatriarch.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, i, 0, i+1, 1));
                        // 输入批注信息
                        comment.setString(new XSSFRichTextString(value));
                        // 将批注添加到单元格对象中
                        sheet.getRow(0).getCell(i).setCellComment(comment);
                    }
                }
            }
        }
    }

}
